require.config({baseUrl: '/js/lib'});
require(['zepto', 'lib'], function ($, lib) {
    var fn = {'map': '', 'geolocation': ''}, lib = new lib();
    $.extend(fn, {
        init: function () {
            fn.getLocation();
            this.bindEvent();
        },
        bindEvent: function () {
            $(document).on('tap', '.ui-show-userInfo', function (e) {
                $('.ui-personal').addClass("slideLeftIn").removeClass("slideLeftOut");
            })
            $(document).on('tap', '.ui-personal', function (e) {
                var target = e.srcElement ? e.srcElement : e.target;
                console.log(target.className)
                if (target.className === "ui-personal slideLeftIn") {
                    $(target).addClass("slideLeftOut").removeClass("slideLeftIn");
                }
            })
        },
        getLocation: function () {
            fn.map = new AMap.Map('container', {
                resizeEnable: true,
                zoom: 12,
                mapStyle:'fresh'
            });
            fn.map.plugin('AMap.Geolocation', function () {
                fn.geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true,//是否使用高精度定位，默认:true
                    timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(20, 120),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: false,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition: 'LB',      //定位按钮位置
                });
                fn.map.addControl(fn.geolocation);
                fn.geolocation.getCurrentPosition();
                AMap.event.addListener(fn.geolocation, 'complete', fn.onLocationComplete);//返回定位信息
                AMap.event.addListener(fn.geolocation, 'error', fn.onLocationError);      //返回定位出错信息
            });
        },
        onLocationComplete: function (data) {
            var addr = data.formattedAddress;
            addr = addr.length > 20 ? addr.substring(0, 20) + '...' : addr;
            $('#localtion-now').html(addr);
            if (data.accuracy) {
                console.log('gps定位成功，精度：' + data.accuracy + ' 米');
            }
            var param = {
                'lon': data.position.getLng(),
                'lat': data.position.getLat()
            };
            $('.ui-nearly-bar').attr('href', '/nearby_city_wine.html?lon=' + param.lon + '&lat=' + param.lat);
            $('.ui-icon-search').attr('href', '/search.html?lon=' + param.lon + '&lat=' + param.lat);

            lib.ajx(lib.getReq().ser + 'storage/searchCoord.action', param, function (data) {
                    if (data.infocode == '0') {
                        var markers = [];
                        var sidArr = [];
                        var info = data.info;
                        for (var i in info) {
                            var maker = new AMap.Marker({
                                map : fn.map,
                                position: [info[i].longitude, info[i].latitude],//marker所在的位置
                                icon: new AMap.Icon({
                                    size: new AMap.Size(20, 30),  //图标大小
                                    image: '/images/zuobiao.png'
                                })
                            });
                            //maker.setMap(fn.map);
                            markers.push(maker);
                            sidArr.push(info[i].storageId);
                        }
                        //绑定点击事件
                        for(var k in markers){
                            (function(index){
                                markers[index].on('click', function () {
                                    location.href = '/wine_shop.html?sId=' + sidArr[index];  //TODO 重复绑定问题待解决
                                });

                            })(k)
                        }
                        //信息窗体
                        if (!sessionStorage.isClose) {
                            var infoWindow = new AMap.InfoWindow({
                                autoMove: true,
                                offset: new AMap.Pixel(0, -20),
                                showShadow: true,
                                closeWhenClickMap: true
                            });
                            infoWindow.setContent('点击酒柜可以一键选酒');
                            infoWindow.open(fn.map, [info[0].longitude, info[0].latitude]);
                            infoWindow.on('close', function () {//监听关闭
                                sessionStorage.isClose = true;
                            });
                        }
                    } else {
                        alert('服务器开小差了，请稍后再试。')
                    }
                },
                function () {
                    console.log('index.js => searchCoord.action fail!');
                })
        },
        onLocationError: function (data) {
            alert('定位失败了，为了更好的为您服务，请稍后重试并开启定位服务！');
            $('.ui-nearly-bar').attr('href', '/nearby_city_wine.html?lon=116.397389&lat=39.909203');
            $('.ui-icon-search').attr('href', '/search.html?lon=116.397389&lat=39.909203');
            $('#localtion-now').html('定位失败，请开启定位服务！');
        },
    });
    fn.init();
});


// $(".ui-personal").click(function(e){
//   var target = e.srcElement ? e.srcElement : e.target;
//   console.log(target.className)
//   if(target.className === "ui-personal slideLeftIn"){
//     $(this).addClass("slideLeftOut");
//   }
// })
